﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using BartonExtension;
using MySql.Data.MySqlClient;
using SQLWrapper;
using Services.Common;
using Model.App;

namespace Services.Business
{
    public class ISMBusinessServiceProvider : ISMServiceProvider
    {
        public const string ADD_BUSINESS = "add_business";
        public const string GET_BUSINESS = "get_business";
        public const string GET_SINGLE_BUSINESS = "get_single_business";
        public const string LIKE_BIZ = "like_biz";
        public const string COMMENT_BIZ = "comment_business";
        public const string GET_COMMENTS = "get_comments";
        public override Task<ISMServiceResult> doProcess(ISMServiceModel model)
        {
            if(model.operationIdentifier == ADD_BUSINESS)
            {
                ISMNewBizRequest request = model.GetState<ISMNewBizRequest>();
                return AddBiz(request);
            }
            else if(model.operationIdentifier == GET_BUSINESS)
            {
                ISMGetBusinessRequest request = model.GetState<ISMGetBusinessRequest>();
                return GetBiz(request);
            }
            else if(model.operationIdentifier == GET_SINGLE_BUSINESS)
            {
                ISMGetSingleBusinessRequest request = model.GetState<ISMGetSingleBusinessRequest>();
                return GetSingleBiz(request);
            }
            else if(model.operationIdentifier == LIKE_BIZ)
            {
                ISMBusinessLikeRequest request = model.GetState<ISMBusinessLikeRequest>();
                return LikeBiz(request);
            }
            else if(model.operationIdentifier == COMMENT_BIZ)
            {
                ISMBusinessCommentRequest request = model.GetState<ISMBusinessCommentRequest>();
                return CommentBiz(request);
            }
            else if(model.operationIdentifier == GET_COMMENTS)
            {
                ISMGetBusinessCommentsRequest request = model.GetState<ISMGetBusinessCommentsRequest>();
                return LoadBizComments(request);
            }
            return base.defaultProcess();
        }
        private Task<ISMServiceResult> AddBiz(ISMNewBizRequest request)
        {
            return Task.Factory.StartNew<ISMServiceResult>(() =>
                {
                    ISMServiceResult result = new ISMServiceResult();
                    MySQLOperationManager.doSQLOperation(cmd =>
                    {
                        cmd.CommandText = "proc_client_add_business";
                        cmd.Parameters.Add("?_token", request.token, ParameterDirection.Input);
                        cmd.Parameters.Add("?_title", request.title, ParameterDirection.Input);
                        cmd.Parameters.Add("?_summary", request.summary, ParameterDirection.Input);
                        cmd.Parameters.Add("?_content", request.content, ParameterDirection.Input);
                        cmd.Parameters.Add("?_publisher", request.publisherId, ParameterDirection.Input);
                        cmd.Parameters.Add("?_status", request.publish_status, ParameterDirection.Input);
                        cmd.Parameters.Add("?_view_permission", request.view_permission, ParameterDirection.Input);
                        cmd.Parameters.Add("?_image_ids", request.image_ids == null ? "" : request.image_ids, ParameterDirection.Input);
                        cmd.Parameters.Add("?errorcode", MySql.Data.MySqlClient.MySqlDbType.Int32, ParameterDirection.Output);
                        cmd.ExecuteNonQuery();
                        int errorcode = cmd.Parameters["?errorcode"].Value.toInt32().Value;
                        if (errorcode == 0)
                        {

                        }
                        else if (errorcode == -1)
                        {
                            result.isOperationSuccess = false;
                            result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_BUSINESS_DUMPLICATED_BUSINESS;
                            result.errorMsg = "你已发布该商讯";
                        }
                        else if (errorcode == -2)
                        {
                            result.isOperationSuccess = false;
                            result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_TOKEN_ERROR;
                            result.errorMsg = "Token 验证失败";
                        }
                    },
                    e =>
                    {
                        if (e != null)
                        {
                            result.isOperationSuccess = false;
                            result.errorMsg = e;
                        }
                    }, CommandType.StoredProcedure, false);
                    return result;
                });
        }
        private Task<ISMServiceResult> GetBiz(ISMGetBusinessRequest request)
        {
            return Task.Factory.StartNew<ISMServiceResult>(() =>
                {
                    ISMServiceResult result = new ISMServiceResult();
                    MySQLOperationManager.doSQLOperationWithLoadedData(cmd =>
                        {
                            cmd.CommandText = "proc_client_get_business";
                            cmd.Parameters.Add("?_uid", request.uid, ParameterDirection.Input);
                            cmd.Parameters.Add("?startIdx", request.page * request.pageSize, ParameterDirection.Input);
                            cmd.Parameters.Add("?endIdx", (request.page + 1) * request.pageSize, ParameterDirection.Input);
                            cmd.Parameters.Add("?_token", request.token, ParameterDirection.Input);
                        },
                        e =>
                        {
                            if(e != null)
                            {
                                result.isOperationSuccess = false;
                                result.errorMsg = e;
                                result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_EXCEPTION_ERR;
                            }
                        },
                        data =>
                        {
                            if(data.Count == 1 && data.First().ContainsKey("error"))
                            {
                                result.isOperationSuccess = false;
                                result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_TOKEN_ERROR;
                                result.errorMsg = "Token 验证失败";
                            }
                            else
                            {
                                List<ISMBusiness> businesses = new List<ISMBusiness>();
                                data.ForEach(d =>
                                    {
                                        ISMBusiness business = new ISMBusiness()
                                        {
                                            ID = d["ID"].toInt64().Value,
                                            title = d["biz_title"].ToString(),
                                            summary = d["biz_summary"].ToString(),
                                            content = d["biz_content"].ToString(),
                                            publish_status = d["biz_status"].toEnum<PublishStatus>(),
                                            view_permission = d["biz_view_permission"].toEnum<ViewPermission>(),
                                            timetag = d["timetag"].ToString(),
                                            comments = d["num_comments"].toUInt64().Value,
                                            likes = d["num_likes"].toUInt64().Value,
                                            liketag = d["liketag"].toBoolean().Value,
                                            publisher = new ISMUserinfo()
                                            {
                                                ID = d["uid"].ToString().toInt64().Value,
                                                openId = d["openid"].ToString(),
                                                intopenid = d["intopenid"].ToString(),
                                                wechatName = d["wechatname"].ToString(),
                                                username = d["username"].ToString(),
                                                sex = (Sex)d["sex"].ToString().toInt32().Value,
                                                vocation = d["vocation"].ToString(),
                                                company = d["company"].ToString(),
                                                occupation = d["occupation"].ToString(),
                                                mobile = d["mobile"].ToString(),
                                                telephone = d["telephone"].ToString(),
                                                email = d["email"].ToString(),
                                                officeAddress = d["officeaddress"].ToString(),
                                                piccardUrl = d["piccardUrl"].ToString(),
                                                videocardUrl = d["piccardUrl"].ToString(),
                                                headimgUrl = d["headimgUrl"].ToString()
                                            },
                                            images = new List<Model.Images.UploadImageEntity>()
                                        };
                                        string imgs = d["img_urls"].ToString();
                                        if(imgs != "#na")
                                        {
                                            int i = 0;
                                            imgs.Split('&').ToList().ForEach(img =>
                                                {
                                                    try
                                                    {
                                                        Model.Images.UploadImageEntity entity = new Model.Images.UploadImageEntity()
                                                        {
                                                            imageID = d["img_ids"].ToString().Split('&')[i].toInt64().Value,
                                                            ori_image_url = img
                                                        };
                                                        entity.generateThumbs();
                                                        business.images.Add(entity);
                                                    }
                                                    catch (Exception e) { }
                                                    i++;
                                                });
                                        }
                                        businesses.Add(business);
                                    });
                                result.dbReturningState = businesses;
                            }
                        }, CommandType.StoredProcedure, false);
                    return result;
                });
        }
        private Task<ISMServiceResult> GetSingleBiz(ISMGetSingleBusinessRequest request)
        {
            return Task.Factory.StartNew<ISMServiceResult>(() =>
                {
                    ISMServiceResult result = new ISMServiceResult();
                    MySQLOperationManager.doSQLOperationWithLoadedData(cmd =>
                        {
                            cmd.CommandText = "proc_client_get_single_business";
                            cmd.Parameters.Add("?_uid", request.uid, ParameterDirection.Input);
                            cmd.Parameters.Add("?_bid", request.bid, ParameterDirection.Input);
                            cmd.Parameters.Add("?_token", request.token, ParameterDirection.Input);
                        },
                        e =>
                        {
                            if(e != null)
                            {
                                result.isOperationSuccess = false;
                                result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_EXCEPTION_ERR;
                                result.errorMsg = e;
                            }
                        },
                        data =>
                        {
                            if(data.Count == 1 && data.First().ContainsKey("error"))
                            {
                                result.isOperationSuccess = false;
                                result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_TOKEN_ERROR;
                                result.errorMsg = "Token 验证失败";
                            }
                            else if(data.Count == 1 && data.First().ContainsKey("biz_not_exists"))
                            {
                                result.isOperationSuccess = false;
                                result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_UNKNOWN_ERR;
                                result.errorMsg = "该商讯不存在";
                            }
                            else if(data.Count == 0)
                            {
                                result.isOperationSuccess = false;
                                result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_AUTHORIZERIGHTSFAIL;
                                result.errorMsg = "无权查看该商讯";
                            }
                            else
                            {
                                var d = data.First();
                                ISMBusiness business = new ISMBusiness()
                                {
                                    ID = d["ID"].toInt64().Value,
                                    title = d["biz_title"].ToString(),
                                    summary = d["biz_summary"].ToString(),
                                    content = d["biz_content"].ToString(),
                                    publish_status = d["biz_status"].toEnum<PublishStatus>(),
                                    view_permission = d["biz_view_permission"].toEnum<ViewPermission>(),
                                    timetag = d["timetag"].ToString(),
                                    comments = d["num_comments"].toUInt64().Value,
                                    likes = d["num_likes"].toUInt64().Value,
                                    liketag = d["liketag"].toBoolean().Value,
                                    publisher = new ISMUserinfo()
                                    {
                                        ID = d["uid"].ToString().toInt64().Value,
                                        openId = d["openid"].ToString(),
                                        intopenid = d["intopenid"].ToString(),
                                        wechatName = d["wechatname"].ToString(),
                                        username = d["username"].ToString(),
                                        sex = (Sex)d["sex"].ToString().toInt32().Value,
                                        vocation = d["vocation"].ToString(),
                                        company = d["company"].ToString(),
                                        occupation = d["occupation"].ToString(),
                                        mobile = d["mobile"].ToString(),
                                        telephone = d["telephone"].ToString(),
                                        email = d["email"].ToString(),
                                        officeAddress = d["officeaddress"].ToString(),
                                        piccardUrl = d["piccardUrl"].ToString(),
                                        videocardUrl = d["piccardUrl"].ToString(),
                                        headimgUrl = d["headimgUrl"].ToString()
                                    },
                                    images = new List<Model.Images.UploadImageEntity>()
                                };
                                string imgs = d["img_urls"].ToString();
                                if (imgs != "#na")
                                {
                                    int i = 0;
                                    imgs.Split('&').ToList().ForEach(img =>
                                    {
                                        try
                                        {
                                            Model.Images.UploadImageEntity entity = new Model.Images.UploadImageEntity()
                                            {
                                                imageID = d["img_ids"].ToString().Split('&')[i].toInt64().Value,
                                                ori_image_url = img
                                            };
                                            entity.generateThumbs();
                                            business.images.Add(entity);
                                        }
                                        catch (Exception e) { }
                                        i++;
                                    });
                                }
                                result.dbReturningState = business;
                            }
                        }, CommandType.StoredProcedure, false);
                    return result;
                });
        }
        private Task<ISMServiceResult> LikeBiz(ISMBusinessLikeRequest request)
        {
            return Task.Factory.StartNew<ISMServiceResult>(() =>
                {
                    ISMServiceResult result = new ISMServiceResult();
                    MySQLOperationManager.doSQLOperation(cmd =>
                        {
                            cmd.CommandText = "proc_client_biz_like";
                            cmd.Parameters.Add("?_uid", request.uid, ParameterDirection.Input);
                            cmd.Parameters.Add("?_bid", request.bid, ParameterDirection.Input);
                            cmd.Parameters.Add("?_isLike", request.isLike, ParameterDirection.Input);
                            cmd.Parameters.Add("?_token", request.token, ParameterDirection.Input);
                            cmd.Parameters.Add("?errorcode", MySqlDbType.Int32, ParameterDirection.Output);
                            cmd.ExecuteNonQuery();
                            int errorcode = cmd.Parameters["?errorcode"].Value.toInt32().Value;
                            if(errorcode == -1)
                            {
                                result.isOperationSuccess = false;
                                result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_TOKEN_ERROR;
                                result.errorMsg = "Token 验证失败";
                            }
                            else if(errorcode == -2)
                            {
                                result.isOperationSuccess = false;
                                result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_BIZ_IS_ALREADY_LIKED;
                                result.errorMsg = "你已赞过该商讯";
                            }
                        },
                        e =>
                        {
                            if(e != null)
                            {
                                result.isOperationSuccess = false;
                                result.errorMsg = e;
                                result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_EXCEPTION_ERR;
                            }
                        },CommandType.StoredProcedure,false);
                    return result;
                });
        }
        private Task<ISMServiceResult> CommentBiz(ISMBusinessCommentRequest request)
        {
            return Task.Factory.StartNew<ISMServiceResult>(() =>
                {
                    ISMServiceResult result = new ISMServiceResult();
                    MySQLOperationManager.doSQLOperation(cmd =>
                        {
                            cmd.CommandText = "proc_client_comment_business";
                            cmd.Parameters.Add("?_bid", request.bid, ParameterDirection.Input);
                            cmd.Parameters.Add("?_uid", request.uid, ParameterDirection.Input);
                            cmd.Parameters.Add("?_comment", request.comment, ParameterDirection.Input);
                            cmd.Parameters.Add("?_token", request.token, ParameterDirection.Input);
                            cmd.Parameters.Add("?errorcode", MySqlDbType.Int32, ParameterDirection.Output);
                            cmd.ExecuteNonQuery();
                            int errorcode = cmd.Parameters["?errorcode"].Value.toInt32().Value;
                            if(errorcode == -1)
                            {
                                result.isOperationSuccess = false;
                                result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_TOKEN_ERROR;
                                result.errorMsg = "Token 验证失败";
                            }
                            else if(errorcode == -2)
                            {
                                result.isOperationSuccess = false;
                                result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_BIZ_DUMPLICATED_COMMENT;
                                result.errorMsg = "无法重复提交相同的评论";
                            }
                        },
                        e =>
                        {
                            if(e != null)
                            {
                                result.isOperationSuccess = false;
                                result.errorMsg = e;
                                result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_EXCEPTION_ERR;
                            }
                        }, CommandType.StoredProcedure, false);
                    return result;
                });
        }
        private Task<ISMServiceResult> LoadBizComments(ISMGetBusinessCommentsRequest request)
        {
            return Task.Factory.StartNew<ISMServiceResult>(() =>
                {
                    ISMServiceResult result = new ISMServiceResult();
                    MySQLOperationManager.doSQLOperationWithLoadedData(cmd =>
                        {
                            cmd.CommandText = "proc_client_get_comments";
                            cmd.Parameters.Add("?_uid", request.uid, ParameterDirection.Input);
                            cmd.Parameters.Add("?_bid", request.bid, ParameterDirection.Input);
                            cmd.Parameters.Add("?startIdx", request.page * request.pageSize, ParameterDirection.Input);
                            cmd.Parameters.Add("?endIdx", (request.page + 1) * request.pageSize, ParameterDirection.Input);
                            cmd.Parameters.Add("?_token", request.token, ParameterDirection.Input);
                        },
                        e =>
                        {
                            if(e != null)
                            {
                                result.isOperationSuccess = false;
                                result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_EXCEPTION_ERR;
                                result.errorMsg = e;
                            }
                        },
                        data =>
                        {
                            if(data.Count == 1 && data.First().ContainsKey("error"))
                            {
                                result.isOperationSuccess = false;
                                result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_TOKEN_ERROR;
                                result.errorMsg = "Token 验证非法";
                            }
                            else
                            {
                                List<ISMBusinessComment> comments = new List<ISMBusinessComment>();
                                data.ForEach(d =>
                                    {
                                        ISMBusinessComment comment = new ISMBusinessComment()
                                        {
                                            ID = d["ID"].toUInt64().Value,
                                            bid = d["bid"].toUInt64().Value,
                                            commentUser = new ISMUserinfo()
                                            {
                                                ID = d["uid"].toInt64().Value,
                                                openId = d["openid"].ToString(),
                                                intopenid = d["intopenid"].toUInt64().Value.ToString(),
                                                wechatName = d["wechatname"].ToString(),
                                                username = d["username"].ToString(),
                                                sex = d["sex"].toEnum<Sex>(),
                                                vocation = d["vocation"].ToString(),
                                                company = d["company"].ToString(),
                                                occupation = d["occupation"].ToString(),
                                                mobile = d["mobile"].ToString(),
                                                telephone = d["telephone"].ToString(),
                                                email = d["email"].ToString(),
                                                officeAddress = d["officeaddress"].ToString(),
                                                piccardUrl = d["piccardUrl"].ToString(),
                                                videocardUrl = d["videocardUrl"].ToString(),
                                                headimgUrl = d["headimgUrl"].ToString()
                                            },
                                            comment = d["comment"].ToString(),
                                            timetag = d["timetag"].ToString()
                                        };
                                        comments.Add(comment);
                                    });
                                result.dbReturningState = comments;
                            }
                        }, CommandType.StoredProcedure, false);
                    return result;
                });
        }
    }
}
